import NProgress from 'nprogress'
import type { RouteRawConfig, RouterTypes, rawConfig } from '~/basic'
import type { RouteRecordName } from 'vue-router'
/**
 * 根据请求，过滤异步路由
 * @param:menuList 异步路由数组
 * return 过滤后的异步路由
 */
// @ts-ignore
import Layout from '@/layout/index.vue'
import CLayout from '@/layout/CLayout.vue'
/*
 * 路由操作
 * */
import router, { asyncRoutes, constantRoutes } from '@/router'
//进度条
import 'nprogress/nprogress.css'
import { useBasicStore } from '@/store/basic'

const buttonCodes: Array<Number> = [] //按钮权限
interface menuRow {
  type: number
  code: number
  path: string
  children: RouterTypes
}
export const filterAsyncRoutesByMenuList = (menuList, path) => {
  const filterRouter: RouterTypes = []
  menuList.forEach((route: menuRow) => {
    //button permission
    if (route.type === 3) {
      buttonCodes.push(route.code)
    } else {
      //generator every router item by menuList
      route.path = path + route.path
      const itemFromReqRouter = getRouteItemFromReqRouter(route)
      if (route.children?.length) {
        //judge  the type is router or button
        itemFromReqRouter.children = filterAsyncRoutesByMenuList(route.children, route.path)
      }
      filterRouter.push(itemFromReqRouter)
    }
  })
  return filterRouter
}
const getRouteItemFromReqRouter = (route): RouteRawConfig => {
  const tmp: rawConfig = { meta: { title: '' } }
  const routeKeyArr = ['path', 'component', 'redirect', 'alwaysShow', 'name', 'hidden']
  const metaKeyArr = ['title', 'iconType', 'affix'] //  'activeMenu', 'cachePage', 'closeTabRmCache'
  // @ts-ignore
  const modules = import.meta.glob('../views/**/**.vue')
  //generator routeKey
  routeKeyArr.forEach((fItem) => {
    if (fItem === 'component') {
      if (route[fItem] === 'Layout') {
        tmp[fItem] = Layout
      } else if (route[fItem] === 'CLayout') {
        tmp[fItem] = CLayout
      } else {
        tmp[fItem] = modules[`../views/${route[fItem]}`]
      }
    } else if (fItem === 'path' && route.parentId === 0) {
      tmp[fItem] = `/${route[fItem]}`
    } else if (['hidden', 'alwaysShow'].includes(fItem)) {
      tmp[fItem] = !!route[fItem]
    } else if (['name'].includes(fItem)) {
      tmp[fItem] = route['code']
    } else if (route[fItem]) {
      tmp[fItem] = route[fItem]
    }
  })
  //generator metaKey
  metaKeyArr.forEach((fItem) => {
    if (fItem === 'iconType' && route.icon && tmp.meta) {
      if (route[fItem] === 1) {
        tmp.meta['elSvgIcon'] = route.icon
      } else {
        tmp.meta['icon'] = route.icon
      }
    }
    if (route[fItem] && tmp.meta) tmp.meta[fItem] = route[fItem]
  })
  return tmp as RouteRawConfig
}

//过滤异步路由
export function filterAsyncRouter({ menus }) {
  const basicStore = useBasicStore()
  let accessRoutes: RouterTypes = []
  accessRoutes = filterAsyncRoutesByMenuList(menus, '') //by menuList
  // eslint-disable-next-line no-console
  console.log(accessRoutes)
  accessRoutes.forEach((route) => router.addRoute(route))
  asyncRoutes.forEach((item) => router.addRoute(item))
  basicStore.setFilterAsyncRoutes(accessRoutes)
}
//重置路由
export function resetRouter() {
  //移除之前存在的路由
  const routeNameSet: Set<RouteRecordName> = new Set()
  router.getRoutes().forEach((fItem) => {
    if (fItem.name) routeNameSet.add(fItem.name)
  })
  routeNameSet.forEach((setItem) => router.removeRoute(setItem))
  //新增constantRoutes
  constantRoutes.forEach((feItem) => router.addRoute(feItem))
}
//重置登录状态
export function resetState() {
  resetRouter()
  useBasicStore().resetState()
}

//刷新路由
export function freshRouter(data) {
  resetRouter()
  filterAsyncRouter(data)
  // location.reload()
}

NProgress.configure({ showSpinner: false })
//开始进度条
export const progressStart = () => {
  NProgress.start()
}
//关闭进度条
export const progressClose = () => {
  NProgress.done()
}
